package server;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Auditor {
	
	private PrintWriter out;
	
	public Auditor(){
		try {
			out = new PrintWriter(new BufferedWriter(new FileWriter("log.txt", true)));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void logon(String username, boolean allowed){	
		if(allowed){
			write("user '" + username + "' successfully logged on");
		}else{
			write("FAILED logon attempt for user '" + username + "'");
		}
	}
	
	public void read(User u, Journal j, boolean allowed){	
		if(allowed){
			write("user '" + u.getName() + "' read journal '" + j.title() + "'");
		}else{
			write("FAILED read attempt of '" + j.title() + "' by user '" + u.getName() + "'");
		}
	}
	
	public void edit(User u, Journal j, boolean allowed){	
		if(allowed){
			write("user '" + u.getName() + "' edited journal '" + j.title() + "'");
		}else{
			write("FAILED edit attempt of '" + j.title() + "' by user '" + u.getName() + "'");
		}
	}
	
	public void remove(User u, Journal j, boolean allowed){	
		if(allowed){
			write("user '" + u.getName() + "' removed journal '" + j.title() + "'");
		}else{
			write("FAILED removal attempt of '" + j.title() + "' by user '" + u.getName() + "'");
		}
	}
	
	public void create(User u, String p, boolean allowed){
		if(allowed){
			write("user '" + u.getName() + "' created new journal for patient '" + p.toString() + "'");
		}else{
			write("FAILED create attempt of journal for patient '" + p.toString() + "' by user '" + u.getName() + "'");
		}
	}
	
	private void write(String text){
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
		out.write(timeStamp + " " + text + "\n");
		out.flush();
	}
}
